<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文章编辑与发布</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/easymde@2.18.0/dist/easymde.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f5f5;
            overflow: auto;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .header h1 {
            font-size: 1.5em;
            font-weight: 300;
        }

        .header-buttons {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }

        .btn-close {
            background: rgba(255, 255, 255, 0.2);
            color: white !important;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }

        .nav-link {
            color: white;
            text-decoration: none;
            padding: 10px 20px; /* 调整内边距 */
            border-radius: 25px; /* 更大的圆角 */
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); /* 紫色渐变背景 */
            transition: all 0.3s ease;
            display: flex; /* 使内容居中 */
            align-items: center;
            gap: 8px; /* 图标和文字之间的间距 */
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2); /* 添加阴影 */
        }

        .nav-link:hover {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%); /* 悬停时渐变反转 */
            transform: translateY(-3px); /* 悬停时上浮 */
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.3); /* 悬停时阴影加深 */
        }

        .nav-link:active {
            transform: translateY(0);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }

        .btn-primary {
            background: rgba(255, 255, 255, 0.2);
            color: red !important;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }

        .btn-primary:hover {
            background: rgba(255, 255, 255, 0.3);
            color: red !important;
        }

        .btn-success {
            background: #28a745;
            color: black !important;
        }

        .btn-success:hover {
            background: #218838;
            color: black !important;
        }

        .btn-info {
            background: #17a2b8;
            color: black!important; /* 将字体颜色改为白色 */
        }

        .btn-info:hover {
            background: #138496;
            color: black !important;
        }

        .btn-warning {
            background: #ffc107;
            color: #212529 !important;
        }

        .btn-warning:hover {
            background: #e0a800;
            color: #212529 !important;
        }

        .btn-secondary {
            background-color: #6c757d;
            color: white !important;
        }

        .btn-secondary:hover {
            background-color: #5a6268;
        }

        .btn-danger {
            background-color: #6c757d; /* 将删除按钮的背景色改为灰色 */
            color: white !important;
        }

        .btn-danger:hover {
            background-color: #5a6268;
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            background-color: #6c757d;
            border-color: #6c757d;
            color: #ffffff !important;
        }

        .template-selector {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-right: 10px;
        }

        .template-selector label {
            font-size: 14px;
            font-weight: 500;
            color: #333;
            white-space: nowrap;
        }

        .template-selector select {
            padding: 6px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            background: white;
            cursor: pointer;
            min-width: 120px;
        }

        .template-selector select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
        }

        .main-container {
            display: flex;
            height: calc(100vh - 70px);
        }

        .sidebar {
            width: 300px;
            background: white;
            border-right: 1px solid #e1e5e9;
            display: flex;
            flex-direction: column;
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid #e1e5e9;
            background: #f8f9fa;
        }

        .sidebar-title {
            font-size: 1.4em; /* 调整字体大小 */
            color: #333;
            margin-bottom: 15px; /* 增加底部间距 */
            display: flex;
            align-items: center;
            gap: 10px; /* 图标和文字间距 */
        }

        .sidebar-title .fas.fa-folder {
            color: #ffc107; /* 将文件夹图标设置为黄色 */
        }

        .file-controls {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
            flex-wrap: wrap;
        }

        .select-controls {
            display: flex;
            gap: 10px; /* 增加按钮之间的间距 */
            margin-bottom: 15px; /* 增加底部间距 */
            font-size: 12px;
            align-items: center; /* 垂直居中 */
        }

        .select-controls button {
            padding: 6px 12px; /* 调整内边距 */
            border-radius: 5px; /* 调整圆角 */
            font-size: 13px; /* 调整字体大小 */
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .tool-link {
            color: #667eea; /* 链接颜色 */
            text-decoration: none; /* 去除下划线 */
            font-size: 14px;
            margin-bottom: 5px; /* 增加底部间距 */
            display: block; /* 使链接独占一行 */
        }

        .tool-link:hover {
            text-decoration: underline; /* 悬停时显示下划线 */
            color: #764ba2;
        }

        .file-list {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }

        .file-item {
            padding: 12px 15px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 5px;
            border: 1px solid transparent;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .file-item:hover {
            background: #f0f0f0;
        }

        .file-item.selected {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .file-item.checked {
            background: #e8f4fd;
            border-color: #007bff;
        }

        .file-item.checked.selected {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .file-checkbox {
            width: 16px;
            height: 16px;
            cursor: pointer;
            flex-shrink: 0;
        }

        .file-info {
            flex: 1;
            min-width: 0;
        }

        .file-name {
            font-weight: 500;
            margin-bottom: 4px;
            word-break: break-word;
        }

        .file-date {
            font-size: 12px;
            opacity: 0.7;
        }

        .editor-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: white;
        }

        .editor-toolbar {
            padding: 15px 20px;
            border-bottom: 1px solid #e1e5e9;
            background: #f8f9fa;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .current-file {
            font-weight: 500;
            color: #333;
        }

        .toolbar-buttons {
            display: flex;
            gap: 10px;
        }

        .editor-wrapper {
            flex: 1;
            padding: 20px;
        }

        .CodeMirror {
            height: calc(100vh - 200px) !important;
            border: 1px solid #e1e5e9;
            border-radius: 6px;
        }

        .CodeMirror-scroll {
            overflow-y: auto !important;
            overflow-x: auto !important;
            max-height: calc(100vh - 200px) !important;
        }

        .CodeMirror-lines {
            padding: 10px;
        }

        .alert {
            padding: 12px 15px;
            border-radius: 6px;
            margin: 10px 20px;
            font-size: 14px;
        }

        .alert-success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .alert-error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }

        .alert-info {
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .loading.show {
            display: block;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }

        .empty-state h3 {
            margin-bottom: 10px;
            color: #999;
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 250px;
            }

            .header-buttons {
                flex-wrap: wrap;
            }

            .toolbar-buttons {
                flex-wrap: wrap;
            }
        }
    </style>
</head>
<body>
<div class="header">
    <h1>📝 文章编辑器</h1>
    <div class="header-buttons">
        <a href="/" class="nav-link">🏠 首页</a>
        <a href="/hot-topic" class="nav-link">🔥 热点采集与分析</a>
        <a href="/multi-generator" class="nav-link">📝 基于主题的文章生成</a>
    </div>
</div>

<div class="main-container">
    <div class="sidebar">
        <div class="sidebar-header">
            <h3 class="sidebar-title"><i class="fas fa-folder"></i> 文章列表</h3>
            <div class="file-controls">
                <button class="btn btn-secondary refresh-btn" onclick="editor.loadFileList()"><i class="fas fa-sync-alt"></i> 刷新</button>
                <button class="btn btn-danger delete-btn" id="delete-btn" onclick="editor.deleteSelectedFiles()" disabled><i class="fas fa-trash-alt"></i> 删除选中</button>
            </div>
            <div class="select-controls">
                <button class="btn btn-info" onclick="editor.selectAll()"><i class="fas fa-check-double"></i> 全选</button>
                <button class="btn btn-warning" onclick="editor.selectNone()"><i class="fas fa-times"></i> 全不选</button>
                <span id="selected-count">已选择: 0</span>
            </div>
            <a href="https://quaily.com/tools/markdown-to-wx/" target="_blank" class="tool-link">跳转到 Markdown 转微信图文工具</a>
            <br><br>
            <a href="https://matrix.tencent.com/ai-detect/ai_gen" target="_blank" class="tool-link">跳转到 AI检查工具</a>
        </div>
        <div class="file-list" id="file-list">
            <div class="loading show">
                <div class="spinner"></div>
                <p>加载中...</p>
            </div>
        </div>
    </div>

    <div class="editor-container">
        <div class="editor-toolbar">
            <div class="current-file" id="current-file">请选择一个文件开始编辑</div>
            <div class="toolbar-buttons">
                <button class="btn btn-success" id="save-btn" onclick="editor.saveFile()" disabled>💾 保存修改</button>
                <div class="template-selector">
                    <label for="template-select">🎨 样式模板:</label>
                    <select id="template-select" disabled>
                        <option value="">随机选择</option>
                    </select>
                </div>
                <button class="btn btn-info" id="convert-btn" onclick="editor.convertToHtml()" disabled>🔄 转换HTML
                </button>
                <button class="btn btn-warning" id="preview-btn" onclick="editor.previewHtml()" disabled>👁️ 查看HTML
                </button>
                <button class="btn btn-primary" id="publish-btn" onclick="editor.publishToWechat()" disabled>📤
                    发布公众号
                </button>
            </div>
        </div>

        <div id="alert-container"></div>

        <div class="editor-wrapper">
            <div class="empty-state" id="empty-state">
                <h3>开始编辑</h3>
                <p>从左侧选择一个Markdown文件开始编辑</p>
            </div>
            <textarea id="markdown-editor" style="display: none;"></textarea>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/easymde@2.18.0/dist/easymde.min.js"></script>
<script>
    class MarkdownEditor {
        constructor() {
            this.currentFile = null;
            this.easyMDE = null;
            this.selectedFiles = new Set();
            this.init();
        }

        init() {
            this.loadFileList();
            this.initEditor();
            this.loadTemplates();
        }

        initEditor() {
            this.easyMDE = new EasyMDE({
                element: document.getElementById('markdown-editor'),
                spellChecker: false,
                autofocus: false,
                placeholder: '开始编写你的文章...',
                toolbar: [
                    'bold', 'italic', 'heading', '|',
                    'quote', 'unordered-list', 'ordered-list', '|',
                    'link', 'image', 'table', '|',
                    'preview', 'side-by-side', 'fullscreen', '|',
                    'guide'
                ],
                status: ['autosave', 'lines', 'words', 'cursor'],
                autosave: {
                    enabled: false
                }
            });
        }

        async loadFileList() {
            const container = document.getElementById('file-list');
            container.innerHTML = `
                    <div class="loading show">
                        <div class="spinner"></div>
                        <p>加载中...</p>
                    </div>
                `;

            try {
                const response = await fetch('/api/articles');
                const result = await response.json();

                if (result.success) {
                    const files = result.data.files;

                    if (files.length > 0) {
                        container.innerHTML = files.map(file => `
                                <div class="file-item" data-filename="${file.name}">
                                    <input type="checkbox" class="file-checkbox" data-filename="${file.name}" 
                                           onchange="editor.onFileCheckboxChange('${file.name}', this.checked)">
                                    <div class="file-info" onclick="editor.loadFile('${file.name}')">
                                        <div class="file-name">${file.name}</div>
                                        <div class="file-date">${file.modified}</div>
                                    </div>
                                </div>
                            `).join('');
                        
                        // 清空选中状态
                        this.selectedFiles.clear();
                        this.updateSelectedCount();
                    } else {
                        container.innerHTML = `
                                <div class="empty-state">
                                    <h3>📄 暂无文章</h3>
                                    <p>还没有生成任何文章</p>
                                </div>
                            `;
                    }
                } else {
                    container.innerHTML = `
                            <div class="alert alert-error">
                                <p>❌ ${result.error}</p>
                            </div>
                        `;
                }
            } catch (error) {
                container.innerHTML = `
                        <div class="alert alert-error">
                            <p>❌ 加载文件列表失败</p>
                        </div>
                    `;
            }
        }

        async loadFile(filename) {
            try {
                const response = await fetch(`/api/articles/${encodeURIComponent(filename)}`);
                const result = await response.json();

                if (result.success) {
                    this.currentFile = filename;
                    this.easyMDE.value(result.data.content);

                    // 更新UI状态
                    document.getElementById('current-file').textContent = filename;
                    document.getElementById('empty-state').style.display = 'none';
                    // markdown-editor元素已被隐藏，不需要显示

                    // 启用按钮
                    document.getElementById('save-btn').disabled = false;
                    document.getElementById('convert-btn').disabled = false;
                    document.getElementById('preview-btn').disabled = false;
                    document.getElementById('publish-btn').disabled = false;
                    document.getElementById('template-select').disabled = false;

                    // 更新选中状态
                    document.querySelectorAll('.file-item').forEach(item => {
                        item.classList.remove('selected');
                    });
                    const selectedItem = document.querySelector(`[data-filename="${filename}"]`);
                    if (selectedItem) {
                        selectedItem.classList.add('selected');
                    }

                    this.showAlert('success', `文件 ${filename} 加载成功`);
                } else {
                    this.showAlert('error', result.error);
                }
            } catch (error) {
                this.showAlert('error', '加载文件失败');
            }
        }

        async saveFile() {
            if (!this.currentFile) {
                this.showAlert('error', '请先选择一个文件');
                return;
            }

            const content = this.easyMDE.value();
            const btn = document.getElementById('save-btn');
            const originalText = btn.textContent;

            btn.disabled = true;
            btn.textContent = '保存中...';

            try {
                const response = await fetch(`/api/articles/${encodeURIComponent(this.currentFile)}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({content})
                });

                const result = await response.json();

                if (result.success) {
                    this.showAlert('success', '文件保存成功');
                } else {
                    this.showAlert('error', result.error);
                }
            } catch (error) {
                this.showAlert('error', '保存文件失败');
            } finally {
                btn.disabled = false;
                btn.textContent = originalText;
            }
        }

        async loadTemplates() {
            try {
                const response = await fetch('/api/templates');
                const result = await response.json();

                if (result.success) {
                    const select = document.getElementById('template-select');
                    const templates = result.data.templates;

                    // 清空现有选项（保留随机选择）
                    select.innerHTML = '<option value="">随机选择</option>';

                    // 添加模板选项
                    templates.forEach(template => {
                        const option = document.createElement('option');
                        option.value = template.name;
                        option.textContent = template.description;
                        select.appendChild(option);
                    });
                } else {
                    console.error('加载模板失败:', result.error);
                }
            } catch (error) {
                console.error('加载模板失败:', error);
            }
        }

        async convertToHtml() {
            if (!this.currentFile) {
                this.showAlert('error', '请先选择一个文件');
                return;
            }

            const btn = document.getElementById('convert-btn');
            const originalText = btn.textContent;
            const templateSelect = document.getElementById('template-select');
            const selectedTemplate = templateSelect.value;

            btn.disabled = true;
            btn.textContent = '转换中...';

            try {
                const requestBody = selectedTemplate ? { template_name: selectedTemplate } : {};
                
                const response = await fetch(`/api/convert-html/${encodeURIComponent(this.currentFile)}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestBody)
                });

                const result = await response.json();

                if (result.success) {
                    const templateUsed = result.data.template_used || '随机选择';
                    this.showAlert('success', `HTML文件已生成: ${result.data.html_path}，使用模板: ${templateUsed}`);
                } else {
                    this.showAlert('error', result.error);
                }
            } catch (error) {
                this.showAlert('error', '转换HTML失败');
            } finally {
                btn.disabled = false;
                btn.textContent = originalText;
            }
        }

        async previewHtml() {
            if (!this.currentFile) {
                this.showAlert('error', '请先选择一个文件');
                return;
            }

            const htmlFilename = this.currentFile.replace('.md', '.html');

            // 检查HTML文件是否存在
            try {
                const response = await fetch(`/preview/${encodeURIComponent(htmlFilename)}`, {
                    method: 'HEAD'
                });

                if (response.status === 404) {
                    this.showAlert('error', '请先生成HTML');
                    return;
                }

                if (!response.ok) {
                    this.showAlert('error', '检查HTML文件失败，请先生成HTML');
                    return;
                }

                window.open(`/preview/${encodeURIComponent(htmlFilename)}`, '_blank');
            } catch (error) {
                this.showAlert('error', '请先生成HTML');
            }
        }

        async publishToWechat() {
            if (!this.currentFile) {
                this.showAlert('error', '请先选择一个文件');
                return;
            }

            const btn = document.getElementById('publish-btn');
            const originalText = btn.textContent;

            btn.disabled = true;
            btn.textContent = '发布中...';

            try {
                const response = await fetch(`/api/publish-wechat/${encodeURIComponent(this.currentFile)}`, {
                    method: 'POST'
                });

                const result = await response.json();

                if (result.success) {
                    this.showAlert('success', `文章已发布到微信草稿箱，Media ID: ${result.data.media_id}`);
                } else {
                    this.showAlert('error', result.error);
                }
            } catch (error) {
                this.showAlert('error', '发布到微信失败');
            } finally {
                btn.disabled = false;
                btn.textContent = originalText;
            }
        }

        onFileCheckboxChange(filename, checked) {
            if (checked) {
                this.selectedFiles.add(filename);
                document.querySelector(`[data-filename="${filename}"]`).classList.add('checked');
            } else {
                this.selectedFiles.delete(filename);
                document.querySelector(`[data-filename="${filename}"]`).classList.remove('checked');
            }
            this.updateSelectedCount();
        }

        selectAll() {
            document.querySelectorAll('.file-checkbox').forEach(checkbox => {
                checkbox.checked = true;
                const filename = checkbox.dataset.filename;
                this.selectedFiles.add(filename);
                document.querySelector(`[data-filename="${filename}"]`).classList.add('checked');
            });
            this.updateSelectedCount();
        }

        selectNone() {
            document.querySelectorAll('.file-checkbox').forEach(checkbox => {
                checkbox.checked = false;
                const filename = checkbox.dataset.filename;
                this.selectedFiles.delete(filename);
                document.querySelector(`[data-filename="${filename}"]`).classList.remove('checked');
            });
            this.updateSelectedCount();
        }

        updateSelectedCount() {
            const count = this.selectedFiles.size;
            document.getElementById('selected-count').textContent = `已选择: ${count}`;
            document.getElementById('delete-btn').disabled = count === 0;
        }

        async deleteSelectedFiles() {
            if (this.selectedFiles.size === 0) {
                this.showAlert('error', '请先选择要删除的文件');
                return;
            }

            if (!confirm(`确定要删除选中的 ${this.selectedFiles.size} 个文件吗？此操作不可撤销！`)) {
                return;
            }

            const btn = document.getElementById('delete-btn');
            const originalText = btn.textContent;

            btn.disabled = true;
            btn.textContent = '删除中...';

            try {
                const filenames = Array.from(this.selectedFiles);
                const response = await fetch('/api/articles/batch-delete', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ filenames })
                });

                const result = await response.json();

                if (result.success) {
                    this.showAlert('success', `成功删除 ${result.data.deleted_count} 个文件`);
                    
                    // 如果当前编辑的文件被删除，清空编辑器
                    if (this.currentFile && this.selectedFiles.has(this.currentFile)) {
                        this.currentFile = null;
                        this.easyMDE.value('');
                        document.getElementById('current-file').textContent = '请选择一个文件开始编辑';
                        document.getElementById('empty-state').style.display = 'block';
                        
                        // 禁用按钮
                        document.getElementById('save-btn').disabled = true;
                        document.getElementById('convert-btn').disabled = true;
                        document.getElementById('preview-btn').disabled = true;
                        document.getElementById('publish-btn').disabled = true;
                        document.getElementById('template-select').disabled = true;
                    }
                    
                    // 重新加载文件列表
                    await this.loadFileList();
                } else {
                    this.showAlert('error', result.error);
                }
            } catch (error) {
                this.showAlert('error', '删除文件失败');
            } finally {
                btn.disabled = false;
                btn.textContent = originalText;
            }
        }

        showAlert(type, message) {
            const container = document.getElementById('alert-container');
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type}`;
            alertDiv.innerHTML = `<p>${message}</p>`;

            container.appendChild(alertDiv);

            // 10秒后自动移除
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.parentNode.removeChild(alertDiv);
                }
            }, 10000);
        }
    }

    // 初始化编辑器
    const editor = new MarkdownEditor();

    // 解析 URL 参数并加载内容
    const params = new URLSearchParams(window.location.search);
    const filePath = params.get('file_path');

    // After the editor is initialized, check for filePath in URL
    if (filePath) {
        // Wait for the editor to be fully initialized before loading the file
        // A small delay to ensure editor.init() has completed its setup
        setTimeout(() => {
            editor.loadFile(filePath);
        }, 100);
    }
</script>
<script>
    function clearHotTopicsCacheAndNavigate() {
        sessionStorage.removeItem('cachedHotTopics');
        window.location.href = '/';
    }
</script>
</body>
</html>